import { NextResponse } from 'next/server';
import { Message } from '../../../lib/db';

// 获取所有消息
export async function GET() {
  try {
    const messages = await Message.findAll({
      order: [['createdAt', 'DESC']]
    });
    return NextResponse.json(messages);
  } catch (error) {
    console.error('获取消息失败:', error);
    return NextResponse.json({ error: '获取消息失败' }, { status: 500 });
  }
}

// 创建新消息
export async function POST(request: Request) {
  try {
    const data = await request.json();
    const { sender, content, timestamp, avatar } = data;

    if (!sender || !content) {
      return NextResponse.json({ error: '发送者和内容不能为空' }, { status: 400 });
    }

    const message = await Message.create({
      sender,
      content,
      timestamp: timestamp || new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
      avatar: avatar || `https://api.dicebear.com/7.x/avataaars/svg?seed=${sender}`
    });

    return NextResponse.json(message);
  } catch (error) {
    console.error('创建消息失败:', error);
    return NextResponse.json({ error: '创建消息失败' }, { status: 500 });
  }
}

// 更新消息
export async function PUT(request: Request) {
  try {
    const data = await request.json();
    const { id, content } = data;

    if (!id || !content) {
      return NextResponse.json({ error: '消息ID和内容不能为空' }, { status: 400 });
    }

    const message = await Message.update(
      { content },
      { where: { id }, returning: true }
    );

    const updatedMessage = await Message.findByPk(id);

    return NextResponse.json(message);
  } catch (error) {
    console.error('更新消息失败:', error);
    return NextResponse.json({ error: '更新消息失败' }, { status: 500 });
  }
}

// 删除消息
export async function DELETE(request: Request) {
  try {
    const data = await request.json();
    const { id } = data;

    if (!id) {
      return NextResponse.json({ error: '消息ID不能为空' }, { status: 400 });
    }

    await Message.destroy({
      where: { id }
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('删除消息失败:', error);
    return NextResponse.json({ error: '删除消息失败' }, { status: 500 });
  }
}